package com.itheima.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.itheima.domain.Standard;
import com.itheima.service.StandardService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard>{
	
	private Standard standard = new Standard();
	
	@Override
	public Standard getModel() {
		// TODO Auto-generated method stub
		return standard;
	}
	@Autowired
	private StandardService standardService;
	
	//注入service
	@Action(value="addStandard",results={@Result(name="success",type="redirect",
			location="./pages/base/standard.html")})
	public String addStandard(){
		standardService.save(standard);
		return SUCCESS;
	}
	//使用属性驱动
	private int page;
	private int rows;
	
	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	@Action(value="page_findStandard",results={@Result(name="success",
			type="json")})
	public String pageStandard(){
		Pageable pageable = new PageRequest(page-1,rows);
		//页面会自动传过来两个参数 rows 和page
		Page<Standard> page = standardService.findPageData(pageable);
		//存到值栈
		//存到值栈之前先要把结果集合装到一个Map集合中 去
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total",page.getTotalElements()); //获得total
		map.put("rows", page.getContent());  //获得rows
		ActionContext.getContext().getValueStack().push(map);
		return "success";
	}
	
	@Action(value="findAllStandard",results={@Result(name="success",
			type="json")})
	public String findAllStandard(){
		List<Standard> list=  standardService.findAll();
		System.out.println(list);
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
}
